#include <string>
#include <iostream>
#include <cmath>
#include <ctime>
#include <chrono>
#include <thread>
#include <fstream>
#include <algorithm>
#include <random>

#include "pve_game.h"

pveGame::pveGame()
{
    // 使用默认皮肤
    this->mCurrentSkinIndex = 0;
    this->setSkinSymbol(0);
    
    // 分离屏幕为三个窗口
    this->mWindows.resize(3);
    initscr();
    nodelay(stdscr, true);
    keypad(stdscr, true);
    noecho();
    curs_set(0);
    
    // 获取屏幕和游戏板参数
    getmaxyx(stdscr, this->mScreenHeight, this->mScreenWidth);
    this->mGameBoardWidth = this->mScreenWidth - this->mInstructionWidth;
    this->mGameBoardHeight = this->mScreenHeight - this->mInformationHeight;

    this->createInformationBoard();
    this->createGameBoard();
    this->createInstructionBoard();

    // 初始化排行榜
    this->mLeaderBoard.assign(this->mNumLeaders, 0);
    
    // 选择难度
    this->selectDifficulty();
    
    // 初始化游戏状态
    this->mGameResult = PvEGameResult::ONGOING;
    this->mFrameCounter = 0;
}

pveGame::pveGame(int skinIndex)
{
    // 使用指定皮肤
    this->mCurrentSkinIndex = skinIndex;
    this->setSkinSymbol(skinIndex);
    
    // 分离屏幕为三个窗口
    this->mWindows.resize(3);
    initscr();
    nodelay(stdscr, true);
    keypad(stdscr, true);
    noecho();
    curs_set(0);
    
    // 获取屏幕和游戏板参数
    getmaxyx(stdscr, this->mScreenHeight, this->mScreenWidth);
    this->mGameBoardWidth = this->mScreenWidth - this->mInstructionWidth;
    this->mGameBoardHeight = this->mScreenHeight - this->mInformationHeight;

    this->createInformationBoard();
    this->createGameBoard();
    this->createInstructionBoard();

    // 初始化排行榜
    this->mLeaderBoard.assign(this->mNumLeaders, 0);
    
    // 选择难度
    this->selectDifficulty();
    
    // 初始化游戏状态
    this->mGameResult = PvEGameResult::ONGOING;
    this->mFrameCounter = 0;
}

pveGame::~pveGame()
{
    for (int i = 0; i < this->mWindows.size(); i++)
    {
        if (this->mWindows[i] != nullptr)
        {
            delwin(this->mWindows[i]);
            this->mWindows[i] = nullptr;
        }
    }
    endwin();
}

void pveGame::createInformationBoard()
{
    this->mWindows[0] = newwin(this->mInformationHeight, this->mScreenWidth, 0, 0);
    box(this->mWindows[0], 0, 0);
}

void pveGame::renderInformationBoard() const
{
    wclear(this->mWindows[0]);
    box(this->mWindows[0], 0, 0);

    mvwprintw(this->mWindows[0], 1, 1, "PvE Mode - Player vs AI");
    mvwprintw(this->mWindows[0], 2, 1, "Player vs AI (>) - Difficulty: %s", this->getDifficultyName().c_str());
    mvwprintw(this->mWindows[0], 3, 1, "Enhanced Version with AI opponent");
    mvwprintw(this->mWindows[0], 4, 1, "Website: https://gitee.com/jyy16/snakegame");

    wrefresh(this->mWindows[0]);
}

void pveGame::createGameBoard()
{
    this->mWindows[1] = newwin(this->mGameBoardHeight, this->mGameBoardWidth, this->mInformationHeight, 0);
    box(this->mWindows[1], 0, 0);
}

void pveGame::renderGameBoard() const
{
    wclear(this->mWindows[1]);
    box(this->mWindows[1], 0, 0);
    wrefresh(this->mWindows[1]);
}

void pveGame::createInstructionBoard()
{
    this->mWindows[2] = newwin(this->mGameBoardHeight, this->mInstructionWidth, this->mInformationHeight, this->mGameBoardWidth);
    box(this->mWindows[2], 0, 0);
}

void pveGame::renderInstructionBoard() const
{
    wclear(this->mWindows[2]);
    box(this->mWindows[2], 0, 0);

    mvwprintw(this->mWindows[2], 1, 1, "PvE Controls");
    mvwprintw(this->mWindows[2], 3, 1, "Player:");
    mvwprintw(this->mWindows[2], 4, 1, "Up:    W");
    mvwprintw(this->mWindows[2], 5, 1, "Down:  S");
    mvwprintw(this->mWindows[2], 6, 1, "Left:  A");
    mvwprintw(this->mWindows[2], 7, 1, "Right: D");
    mvwprintw(this->mWindows[2], 8, 1, "Pause/Resume: P");
    mvwprintw(this->mWindows[2], 9, 1, "Rules: H");

    mvwprintw(this->mWindows[2], 11, 1, "Difficulty");
    mvwprintw(this->mWindows[2], 14, 1, "Scores");

    wrefresh(this->mWindows[2]);
}

void pveGame::renderLeaderBoard() const
{
    // 如果空间不够，跳过渲染排行榜
    if (this->mScreenHeight - this->mInformationHeight - 18 - 2 < 3 * 2)
    {
        return;
    }
    mvwprintw(this->mWindows[2], 18, 1, "Leader Board");
    std::string pointString;
    std::string rank;
    for (int i = 0; i < std::min(this->mNumLeaders, this->mScreenHeight - this->mInformationHeight - 18 - 2); i++)
    {
        pointString = std::to_string(this->mLeaderBoard[i]);
        rank = "#" + std::to_string(i + 1) + ":";
        mvwprintw(this->mWindows[2], 18 + (i + 1), 1, rank.c_str());
        mvwprintw(this->mWindows[2], 18 + (i + 1), 5, pointString.c_str());
    }
    wrefresh(this->mWindows[2]);
}

bool pveGame::renderRestartMenu() const
{
    WINDOW* menu;
    int width = 30;
    int height = 10;
    int startX = this->mGameBoardWidth / 2 - width / 2;
    int startY = this->mGameBoardHeight / 2 - height / 2;
    
    menu = newwin(height, width, startY, startX);
    box(menu, 0, 0);
    
    switch(this->mGameResult)
    {
        case PvEGameResult::PLAYER_WIN:
            mvwprintw(menu, 1, 1, "Player Wins!");
            mvwprintw(menu, 2, 1, "Player: %d  AI: %d", this->mPlayerPoints, this->mAIPoints);
            break;
        case PvEGameResult::AI_WIN:
            mvwprintw(menu, 1, 1, "AI Wins!");
            mvwprintw(menu, 2, 1, "Player: %d  AI: %d", this->mPlayerPoints, this->mAIPoints);
            break;
        case PvEGameResult::DRAW:
            mvwprintw(menu, 1, 1, "Draw!");
            mvwprintw(menu, 2, 1, "Player: %d  AI: %d", this->mPlayerPoints, this->mAIPoints);
            break;
        default:
            mvwprintw(menu, 1, 1, "Game Over!");
            break;
    }
    
    mvwprintw(menu, 4, 1, "Press:");
    mvwprintw(menu, 5, 1, "R - Restart");
    mvwprintw(menu, 6, 1, "Q - Quit");
    
    wrefresh(menu);
    
    int key;
    while (true)
    {
        key = getch();
        switch (key)
        {
            case 'r':
            case 'R':
                delwin(menu);
                return true;
            case 'q':
            case 'Q':
                delwin(menu);
                return false;
            default:
                break;
        }
    }
}

void pveGame::renderPoints() const
{
    mvwprintw(this->mWindows[2], 15, 1, "P: %d", this->mPlayerPoints);
    mvwprintw(this->mWindows[2], 16, 1, "A: %d", this->mAIPoints);
    wrefresh(this->mWindows[2]);
}

void pveGame::renderDifficulty() const
{
    mvwprintw(this->mWindows[2], 12, 1, "%s", this->getDifficultyName().c_str());
    wrefresh(this->mWindows[2]);
}

void pveGame::initializeGame()
{
    this->mPlayerSnake = std::make_unique<Snake>(this->mGameBoardWidth, this->mGameBoardHeight, this->mInitialSnakeLength);
    this->mAISnake = std::make_unique<Snake>(this->mGameBoardWidth, this->mGameBoardHeight, this->mInitialSnakeLength);
    
    // 设置玩家蛇的初始位置（左侧）
    this->mPlayerSnake->setPosition(this->mGameBoardWidth / 4, this->mGameBoardHeight / 2);
    
    // 设置AI蛇的初始位置（右侧）
    this->mAISnake->setPosition(3 * this->mGameBoardWidth / 4, this->mGameBoardHeight / 2);
    
    // 初始化AI方向
    this->mCurrentAIDirection = Direction::Up;
    
    this->createRamdonFood();
    
    this->mPlayerPoints = 0;
    this->mAIPoints = 0;
    this->mDifficulty = 0;
    this->mGameResult = PvEGameResult::ONGOING;
    this->mFrameCounter = 0;
    
    this->mDelay = this->mBaseDelay;
}

void pveGame::createRamdonFood()
{
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> disX(1, this->mGameBoardWidth - 2);
    std::uniform_int_distribution<> disY(1, this->mGameBoardHeight - 2);
    
    int foodX, foodY;
    do
    {
        foodX = disX(gen);
        foodY = disY(gen);
    } while (this->mPlayerSnake->isPartOfSnake(foodX, foodY) || this->mAISnake->isPartOfSnake(foodX, foodY));
    
    this->mFood = SnakeBody(foodX, foodY);
    this->mPlayerSnake->senseFood(this->mFood);
    this->mAISnake->senseFood(this->mFood);
}

void pveGame::renderFood() const
{
    mvwaddch(this->mWindows[1], this->mFood.getY(), this->mFood.getX(), this->mFoodSymbol);
    wrefresh(this->mWindows[1]);
}

void pveGame::renderSnakes() const
{
    // 渲染玩家蛇
    std::vector<SnakeBody>& playerSnakeBody = this->mPlayerSnake->getSnake();
    for (int i = 0; i < playerSnakeBody.size(); i++)
    {
        mvwaddch(this->mWindows[1], playerSnakeBody[i].getY(), playerSnakeBody[i].getX(), 
                 i == 0 ? this->mCurrentPlayerSnakeSymbol : this->mCurrentPlayerSnakeSymbol);
    }
    
    // 渲染AI蛇
    std::vector<SnakeBody>& aiSnakeBody = this->mAISnake->getSnake();
    for (int i = 0; i < aiSnakeBody.size(); i++)
    {
        mvwaddch(this->mWindows[1], aiSnakeBody[i].getY(), aiSnakeBody[i].getX(), 
                 i == 0 ? this->mAISnakeSymbol : this->mAISnakeSymbol);
    }
    
    wrefresh(this->mWindows[1]);
}

PvEGameResult pveGame::checkCollisions()
{
    // 检查玩家蛇碰撞
    bool playerHitWall = this->mPlayerSnake->hitWall();
    bool playerHitSelf = this->mPlayerSnake->hitSelf();
    bool playerHitAI = false;
    
    // 检查玩家蛇是否撞到AI蛇
    SnakeBody playerHead = this->mPlayerSnake->getHead();
    if (this->mAISnake->isPartOfSnake(playerHead.getX(), playerHead.getY()))
    {
        playerHitAI = true;
    }
    
    // 检查AI蛇碰撞
    bool aiHitWall = this->mAISnake->hitWall();
    bool aiHitSelf = this->mAISnake->hitSelf();
    bool aiHitPlayer = false;
    
    // 检查AI蛇是否撞到玩家蛇
    SnakeBody aiHead = this->mAISnake->getHead();
    if (this->mPlayerSnake->isPartOfSnake(aiHead.getX(), aiHead.getY()))
    {
        aiHitPlayer = true;
    }
    
    // 检查头部碰撞
    bool headCollision = (playerHead.getX() == aiHead.getX() && playerHead.getY() == aiHead.getY());
    
    // 判断游戏结果
    if (headCollision)
    {
        return PvEGameResult::DRAW;
    }
    else if (playerHitWall || playerHitSelf || playerHitAI)
    {
        return PvEGameResult::AI_WIN;
    }
    else if (aiHitWall || aiHitSelf || aiHitPlayer)
    {
        return PvEGameResult::PLAYER_WIN;
    }
    
    return PvEGameResult::ONGOING;
}

void pveGame::renderBoards() const
{
    this->renderInformationBoard();
    this->renderGameBoard();
    this->renderInstructionBoard();
    this->renderLeaderBoard();
    this->renderPoints();
    this->renderDifficulty();
    this->renderFood();
    this->renderSnakes();
    if (this->mIsPaused)
    {
        this->renderPauseMenu(); // 只有暂停时才渲染暂停菜单
    }
}

void pveGame::adjustDelay()
{
    this->mDelay = this->mBaseDelay - this->mDifficulty * 10;
    this->mDelay = std::max(this->mDelay, 30);
}

void pveGame::runGame()
{
    bool exitGame = false;
    
    while (!exitGame)
    {
        this->mFrameCounter++;
        
        if (!this->mIsPaused)
        {
            // 处理玩家输入
            int key = getch();
            switch (key)
            {
                case 'w':
                case 'W':
                    this->mPlayerSnake->changeDirection(Direction::Up);
                    break;
                case 's':
                case 'S':
                    this->mPlayerSnake->changeDirection(Direction::Down);
                    break;
                case 'a':
                case 'A':
                    this->mPlayerSnake->changeDirection(Direction::Left);
                    break;
                case 'd':
                case 'D':
                    this->mPlayerSnake->changeDirection(Direction::Right);
                    break;
                case 'p':
                case 'P':
                    this->togglePause();
                    break;
                case 'h':
                case 'H':
                    this->showRuleFile();
                    // 规则窗口退出后，强制重新渲染所有界面
                    werase(this->mWindows[1]);
                    box(this->mWindows[1], 0, 0);
                    break;
                case 'q':
                case 'Q':
                    exitGame = true;
                    break;
            }
            
            // 更新AI
            this->updateAI();
            
            // 移动蛇
            bool playerAteFood = this->mPlayerSnake->moveFoward();
            bool aiAteFood = this->mAISnake->moveFoward();
            
            // 检查食物碰撞
            if (playerAteFood)
            {
                this->mPlayerPoints++;
                this->mDifficulty = this->mPlayerPoints / 5;
                this->adjustDelay();
                this->createRamdonFood();
            }
            else if (aiAteFood)
            {
                this->mAIPoints++;
                this->createRamdonFood();
            }
            
            // 检查碰撞
            this->mGameResult = this->checkCollisions();
            
            if (this->mGameResult != PvEGameResult::ONGOING)
            {
                // 更新排行榜
                this->updateLeaderBoard();
                
                // 显示重新开始菜单
                if (this->renderRestartMenu())
                {
                    this->initializeGame();
                }
                else
                {
                    exitGame = true;
                }
            }
        }
        else
        {
            // 暂停时处理输入
            int key = getch();
            if (key == 'p' || key == 'P')
            {
                this->togglePause();
            }
            else if (key == 'q' || key == 'Q')
            {
                exitGame = true;
            }
        }
        
        werase(this->mWindows[1]);
        box(this->mWindows[1], 0, 0);

        // 渲染游戏
        this->renderFood();
        this->renderSnakes();
        this->renderPoints();
        this->renderDifficulty();
        
        // 如果暂停，渲染暂停菜单
        if (this->mIsPaused)
        {
            this->renderPauseMenu();
        }
        
        // 延迟
        std::this_thread::sleep_for(std::chrono::milliseconds(this->mDelay));
        refresh();
    }
}

void pveGame::startGame()
{
    this->renderInformationBoard();
    this->readLeaderBoard();
    this->renderInstructionBoard();
    this->initializeGame();
    this->runGame();
    this->writeLeaderBoard();
}

// AI相关方法实现
void pveGame::updateAI()
{
    if (this->mFrameCounter % this->mAIUpdateInterval == 0)
    {
        Direction newDirection = this->calculateAIDirection();
        this->mAISnake->changeDirection(newDirection);
    }
}

Direction pveGame::calculateAIDirection()
{
    SnakeBody aiHead = this->mAISnake->getHead();
    SnakeBody playerHead = this->mPlayerSnake->getHead();
    
    // 获取所有可能的方向
    std::vector<Direction> possibleDirections = {Direction::Up, Direction::Down, Direction::Left, Direction::Right};
    std::vector<Direction> validDirections;
    
    // 过滤出有效方向
    for (Direction dir : possibleDirections)
    {
        if (this->isValidMove(this->mAISnake.get(), dir))
        {
            validDirections.push_back(dir);
        }
    }
    
    if (validDirections.empty())
    {
        return this->mCurrentAIDirection; // 如果没有有效方向，保持当前方向
    }
    
    // 计算每个方向的评分
    std::vector<std::pair<Direction, float>> directionScores;
    
    for (Direction dir : validDirections)
    {
        float score = 0.0f;
        
        // 计算移动后的位置
        SnakeBody nextPos = aiHead;
        switch (dir)
        {
            case Direction::Up:
                nextPos = SnakeBody(aiHead.getX(), aiHead.getY() - 1);
                break;
            case Direction::Down:
                nextPos = SnakeBody(aiHead.getX(), aiHead.getY() + 1);
                break;
            case Direction::Left:
                nextPos = SnakeBody(aiHead.getX() - 1, aiHead.getY());
                break;
            case Direction::Right:
                nextPos = SnakeBody(aiHead.getX() + 1, aiHead.getY());
                break;
        }
        
        // 1. 食物吸引力
        int foodDistance = this->calculateDistance(nextPos, this->mFood);
        score += 100.0f / (foodDistance + 1);
        
        // 2. 攻击性：靠近玩家
        int playerDistance = this->calculateDistance(nextPos, playerHead);
        score += this->mAIAggressiveness * 50.0f / (playerDistance + 1);
        
        // 3. 避免危险：远离边界
        int wallDistance = std::min(std::min(nextPos.getX(), nextPos.getY()), 
                                   std::min(this->mGameBoardWidth - nextPos.getX() - 1,
                                          this->mGameBoardHeight - nextPos.getY() - 1));
        score += wallDistance * 10.0f;
        
        // 4. 避免自己的身体
        if (this->mAISnake->isPartOfSnake(nextPos.getX(), nextPos.getY()))
        {
            score -= 1000.0f;
        }
        
        // 5. 避免玩家的身体
        if (this->mPlayerSnake->isPartOfSnake(nextPos.getX(), nextPos.getY()))
        {
            score -= 500.0f;
        }
        
        directionScores.push_back({dir, score});
    }
    
    // 选择得分最高的方向
    Direction bestDirection = validDirections[0];
    float bestScore = directionScores[0].second;
    
    for (const auto& pair : directionScores)
    {
        if (pair.second > bestScore)
        {
            bestDirection = pair.first;
            bestScore = pair.second;
        }
    }
    
    return bestDirection;
}

bool pveGame::isValidMove(Snake* snake, Direction dir) const
{
    SnakeBody head = snake->getHead();
    SnakeBody nextPos = head;
    
    switch (dir)
    {
        case Direction::Up:
            nextPos = SnakeBody(head.getX(), head.getY() - 1);
            break;
        case Direction::Down:
            nextPos = SnakeBody(head.getX(), head.getY() + 1);
            break;
        case Direction::Left:
            nextPos = SnakeBody(head.getX() - 1, head.getY());
            break;
        case Direction::Right:
            nextPos = SnakeBody(head.getX() + 1, head.getY());
            break;
    }
    
    // 检查是否撞墙
    if (nextPos.getX() <= 0 || nextPos.getX() >= this->mGameBoardWidth - 1 ||
        nextPos.getY() <= 0 || nextPos.getY() >= this->mGameBoardHeight - 1)
    {
        return false;
    }
    
    // 检查是否撞到自己
    if (snake->isPartOfSnake(nextPos.getX(), nextPos.getY()))
    {
        return false;
    }
    
    return true;
}

int pveGame::calculateDistance(const SnakeBody& pos1, const SnakeBody& pos2) const
{
    return std::abs(pos1.getX() - pos2.getX()) + std::abs(pos1.getY() - pos2.getY());
}

// 文件操作方法
bool pveGame::readLeaderBoard()
{
    std::ifstream file(this->mRecordBoardFilePath);
    if (!file.is_open())
    {
        return false;
    }
    
    for (int i = 0; i < this->mNumLeaders; i++)
    {
        if (!(file >> this->mLeaderBoard[i]))
        {
            file.close();
            return false;
        }
    }
    
    file.close();
    return true;
}

bool pveGame::updateLeaderBoard()
{
    // 只有玩家获胜时才更新排行榜
    if (this->mGameResult == PvEGameResult::PLAYER_WIN)
    {
        this->mLeaderBoard.push_back(this->mPlayerPoints);
        std::sort(this->mLeaderBoard.begin(), this->mLeaderBoard.end(), std::greater<int>());
        this->mLeaderBoard.resize(this->mNumLeaders);
        return true;
    }
    return false;
}

bool pveGame::writeLeaderBoard()
{
    std::ofstream file(this->mRecordBoardFilePath);
    if (!file.is_open())
    {
        return false;
    }
    
    for (int i = 0; i < this->mNumLeaders; i++)
    {
        file << this->mLeaderBoard[i] << std::endl;
    }
    
    file.close();
    return true;
}

// 暂停相关方法
void pveGame::togglePause()
{
    this->mIsPaused = !this->mIsPaused;
}

void pveGame::renderPauseMenu() const
{
    if (this->mIsPaused)
    {
        WINDOW* pauseWindow;
        int width = 20;
        int height = 6;
        int startX = this->mGameBoardWidth / 2 - width / 2;
        int startY = this->mGameBoardHeight / 2 - height / 2;
        
        pauseWindow = newwin(height, width, startY, startX);
        box(pauseWindow, 0, 0);
        
        mvwprintw(pauseWindow, 1, 1, "PAUSED");
        mvwprintw(pauseWindow, 2, 1, "Press P to resume");
        mvwprintw(pauseWindow, 3, 1, "Press Q to quit");
        
        wrefresh(pauseWindow);
        delwin(pauseWindow);
    }
}

bool pveGame::isPaused() const
{
    return this->mIsPaused;
}

// 皮肤相关方法
void pveGame::setSkinSymbol(int skinIndex)
{
    this->mCurrentSkinIndex = skinIndex;
    this->mCurrentPlayerSnakeSymbol = this->getSkinSymbol(skinIndex);
}

char pveGame::getSkinSymbol(int skinIndex) const
{
    switch (skinIndex)
    {
        case 0:
            return 'O';  // skin1
        case 1:
            return '$';  // skin2
        case 2:
            return '~';  // skin3
        default:
            return '@';  // 默认
    }
}

void pveGame::selectDifficulty()
{
    // 创建难度选择对话框
    int dialogHeight = 10;
    int dialogWidth = 50;
    int startY = (this->mScreenHeight - dialogHeight) / 2;
    int startX = (this->mScreenWidth - dialogWidth) / 2;
    
    WINDOW* dialogWin = newwin(dialogHeight, dialogWidth, startY, startX);
    keypad(dialogWin, TRUE);
    
    int currentChoice = 1; // 默认选择Medium
    int key;
    
    while (true)
    {
        wclear(dialogWin);
        box(dialogWin, 0, 0);
        
        // 标题
        mvwprintw(dialogWin, 1, (dialogWidth - 17) / 2, "Select Difficulty");
        
        // 选项
        const char* options[] = {"Easy", "Medium", "Hard"};
        
        for (int i = 0; i < 3; i++)
        {
            if (i == currentChoice)
            {
                wattron(dialogWin, A_REVERSE);
                mvwprintw(dialogWin, 3 + i, 2, "> %s", options[i]);
                wattroff(dialogWin, A_REVERSE);
            }
            else
            {
                mvwprintw(dialogWin, 3 + i, 2, "  %s", options[i]);
            }
        }
        
        mvwprintw(dialogWin, 7, 2, "Use W/S to navigate, Enter to select");
        
        wrefresh(dialogWin);
        
        key = wgetch(dialogWin);
        
        switch (key)
        {
            case 'w':
            case 'W':
            case KEY_UP:
                currentChoice = (currentChoice - 1 + 3) % 3;
                break;
            case 's':
            case 'S':
            case KEY_DOWN:
                currentChoice = (currentChoice + 1) % 3;
                break;
            case '\n':
            case '\r':
            case KEY_ENTER:
                this->setDifficulty(static_cast<PvEDifficulty>(currentChoice));
                delwin(dialogWin);
                return;
            default:
                break;
        }
    }
}

void pveGame::setDifficulty(PvEDifficulty difficulty)
{
    this->mSelectedDifficulty = difficulty;
    
    // 根据难度设置AI参数
    switch (difficulty)
    {
        case PvEDifficulty::EASY:
            this->mDifficultyAggressiveness = 0.4f;
            this->mDifficultyReactionTime = 4;
            this->mDifficultyAIUpdateInterval = 5;
            break;
        case PvEDifficulty::MEDIUM:
            this->mDifficultyAggressiveness = 0.7f;
            this->mDifficultyReactionTime = 2;
            this->mDifficultyAIUpdateInterval = 3;
            break;
        case PvEDifficulty::HARD:
            this->mDifficultyAggressiveness = 0.9f;
            this->mDifficultyReactionTime = 1;
            this->mDifficultyAIUpdateInterval = 2;
            break;
    }
    
    // 更新AI参数
    this->mAIAggressiveness = this->mDifficultyAggressiveness;
    this->mAIReactionTime = this->mDifficultyReactionTime;
    this->mAIUpdateInterval = this->mDifficultyAIUpdateInterval;
}

std::string pveGame::getDifficultyName() const
{
    switch (this->mSelectedDifficulty)
    {
        case PvEDifficulty::EASY:
            return "Easy";
        case PvEDifficulty::MEDIUM:
            return "Medium";
        case PvEDifficulty::HARD:
            return "Hard";
        default:
            return "Unknown";
    }
}

void pveGame::showRuleFile() 
{
    // 创建规则显示窗口
    int dialogHeight = this->mScreenHeight - 4;
    int dialogWidth = this->mScreenWidth - 4;
    int startY = 2;
    int startX = 2;
    
    WINDOW* ruleWin = newwin(dialogHeight, dialogWidth, startY, startX);
    keypad(ruleWin, TRUE);
    
    // 读取rule.txt文件
    std::vector<std::string> ruleLines;
    std::ifstream ruleFile("rule.txt");
    
    if (ruleFile.is_open())
    {
        std::string line;
        while (std::getline(ruleFile, line))
        {
            ruleLines.push_back(line);
        }
        ruleFile.close();
    }
    else
    {
        ruleLines.push_back("Error: Cannot open rule.txt file");
        ruleLines.push_back("Please make sure rule.txt exists in the game directory");
    }
    
    int scrollOffset = 0;
    int maxDisplayLines = dialogHeight - 4; // 减去边框和标题行
    int key;
    
    while (true)
    {
        wclear(ruleWin);
        box(ruleWin, 0, 0);
        
        // 标题
        mvwprintw(ruleWin, 1, (dialogWidth - 15) / 2, "PvE Game Rules");
        
        // 显示规则内容
        int displayLine = 2;
        for (int i = scrollOffset; i < static_cast<int>(ruleLines.size()) && displayLine < dialogHeight - 2; i++)
        {
            // 处理长行，如果超过窗口宽度则截断
            std::string line = ruleLines[i];
            if (line.length() > static_cast<size_t>(dialogWidth - 4))
            {
                line = line.substr(0, dialogWidth - 4);
            }
            mvwprintw(ruleWin, displayLine, 2, "%s", line.c_str());
            displayLine++;
        }
        
        // 底部控制提示
        mvwprintw(ruleWin, dialogHeight - 2, 2, "Controls: W/S or Arrow Keys to scroll, Q to close");
        
        // 如果有更多内容可以滚动，显示滚动指示器
        if (scrollOffset > 0)
        {
            mvwprintw(ruleWin, 2, dialogWidth - 3, "^");
        }
        if (scrollOffset + maxDisplayLines < static_cast<int>(ruleLines.size()))
        {
            mvwprintw(ruleWin, dialogHeight - 3, dialogWidth - 3, "v");
        }
        
        wrefresh(ruleWin);
        
        key = wgetch(ruleWin);
        
        switch (key)
        {
            case 'w':
            case 'W':
            case KEY_UP:
                if (scrollOffset > 0)
                    scrollOffset--;
                break;
            case 's':
            case 'S':
            case KEY_DOWN:
                if (scrollOffset + maxDisplayLines < static_cast<int>(ruleLines.size()))
                    scrollOffset++;
                break;
            case 'q':
            case 'Q':
                delwin(ruleWin);
                // 清屏并重新渲染所有界面以覆盖规则窗口
                clear();
                refresh();
                // 重新创建和渲染所有窗口
                this->createInformationBoard();
                this->createGameBoard();
                this->createInstructionBoard();
                this->renderBoards();
                return;
            default:
                break;
        }
    }
}
